<template>
  <Dialog v-model="dialogVisible" :appendToBody="true" :title="props.placeholder">
    <ContentWrap>
      <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
      >
        <el-form-item label="关键词" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            class="!w-240px"
            clearable
            placeholder="请输入店铺名称或联系人电话"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="list" show-overflow-tooltip>
        <template #empty>
          <div class="text-center text-red-500">请先输入店铺名称或联系人电话搜索</div>
        </template>
        <!-- 1. 多选模式（不能使用type="selection"，Element会忽略Header插槽） -->
        <el-table-column width="55" v-if="props.multiple">
          <template #header>
            <el-checkbox
              v-model="isCheckAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAll"
            />
          </template>
          <template #default="{ row }">
            <el-checkbox
              v-model="checkedStatus[row.id]"
              @change="(checked: boolean) => handleCheckOne(checked, row, true)"
            />
          </template>
        </el-table-column>
        <!-- 2. 单选模式 -->
        <el-table-column label="#" width="55" v-else>
          <template #default="{ row }">
            <el-radio :value="row.id" v-model="selectedShopId" @change="handleSingleSelected(row)">
              <!-- 空格不能省略，是为了让单选框不显示label，如果不指定label不会有选中的效果 -->
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column label="徽标" min-width="80">
          <template #default="{ row }">
            <el-image
              :src="row.logo"
              class="h-30px w-30px"
              :preview-src-list="[row.logo]"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" min-width="200" prop="name" />
        <el-table-column label="联系人" min-width="150">
          <template #default="scope">
            <el-text>{{ scope.row.contactName || '不详' }}</el-text>
            <br />
            <el-text>{{ scope.row.contactMobile || '不详' }}</el-text>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <template #footer v-if="props.multiple">
      <el-button type="primary" @click="handleEmitChange">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <template #footer v-else>
      <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { propTypes } from '@/utils/propTypes'
import { ShopInfoApi, ShopInfoVO } from '@/api/mall/shop/info'
import { CHANGE_EVENT } from 'element-plus'

defineOptions({ name: 'ShopTableSelect' })

const props = defineProps({
  // 多选模式
  multiple: propTypes.bool.def(false),
  placeholder: propTypes.string.def('请选择店铺')
})

// 列表的数据
const list = ref<ShopInfoVO[]>([])
// 列表的加载中
const loading = ref(false)
// 弹窗的是否展示
const dialogVisible = ref(false)
// 查询参数
const queryParams = ref({
  keyword: ''
})

/** 打开弹窗 */
const open = (shopList?: ShopInfoVO[]) => {
  // 重置
  checkedShops.value = []
  checkedStatus.value = {}
  isCheckAll.value = false
  isIndeterminate.value = false

  // 处理已选中
  if (shopList && shopList.length > 0) {
    checkedShops.value = [...shopList]
    checkedStatus.value = Object.fromEntries(shopList.map((shop) => [shop.id, true]))
  }

  dialogVisible.value = true
  resetQuery()
}
// 提供 open 方法，用于打开弹窗
defineExpose({ open })

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    if (queryParams.value.keyword) {
      const data = await ShopInfoApi.searchShopInfoSimpleList(queryParams.value.keyword)
      list.value = data
    } else {
      list.value = []
    }
    // checkbox绑定undefined会有问题，需要给一个bool值
    list.value.forEach(
      (shop) => (checkedStatus.value[shop.id] = checkedStatus.value[shop.id] || false)
    )
    // 计算全选框状态
    calculateIsCheckAll()
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    keyword: ''
  }
  getList()
}

// 是否全选
const isCheckAll = ref(false)
// 全选框是否处于中间状态：不是全部选中 && 任意一个选中
const isIndeterminate = ref(false)
// 选中的店铺
const checkedShops = ref<ShopInfoVO[]>([])
// 选中状态：key为店铺ID，value为是否选中
const checkedStatus = ref<Record<string, boolean>>({})

// 选中的店铺 shopId
const selectedShopId = ref()
/** 单选中时触发 */
const handleSingleSelected = (shop: ShopInfoVO) => {
  emits(CHANGE_EVENT, shop)
  // 关闭弹窗
  dialogVisible.value = false
  // 记住上次选择的ID
  selectedShopId.value = shop.id
}

/** 多选完成 */
const handleEmitChange = () => {
  // 关闭弹窗
  dialogVisible.value = false
  emits(CHANGE_EVENT, [...checkedShops.value])
}

/** 确认选择时的触发事件 */
const emits = defineEmits<{
  change: [shop: ShopInfoVO | ShopInfoVO[] | any]
}>()

/** 全选/全不选 */
const handleCheckAll = (checked: boolean) => {
  isCheckAll.value = checked
  isIndeterminate.value = false

  list.value.forEach((shop) => handleCheckOne(checked, shop, false))
}

/**
 * 选中一行
 * @param checked 是否选中
 * @param shop 店铺
 * @param isCalcCheckAll 是否计算全选
 */
const handleCheckOne = (checked: boolean, shop: ShopInfoVO, isCalcCheckAll: boolean) => {
  if (checked) {
    checkedShops.value.push(shop)
    checkedStatus.value[shop.id] = true
  } else {
    const index = findCheckedIndex(shop)
    if (index > -1) {
      checkedShops.value.splice(index, 1)
      checkedStatus.value[shop.id] = false
      isCheckAll.value = false
    }
  }

  // 计算全选框状态
  if (isCalcCheckAll) {
    calculateIsCheckAll()
  }
}

// 查找店铺在已选中店铺列表中的索引
const findCheckedIndex = (shop: ShopInfoVO) =>
  checkedShops.value.findIndex((item) => item.id === shop.id)

// 计算全选框状态
const calculateIsCheckAll = () => {
  isCheckAll.value = list.value.every((shop) => checkedStatus.value[shop.id])
  // 计算中间状态：不是全部选中 && 任意一个选中
  isIndeterminate.value =
    !isCheckAll.value && list.value.some((shop) => checkedStatus.value[shop.id])
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
